<script setup lang="ts">
import { useMap } from "@/views/pipe-network/components/Map/index.vue";
import { ref } from "vue";
import { LPolyline, LCircle, LMarker } from "@vue-leaflet/vue-leaflet";
import { useMapStore } from "@/store";
import { MAP_ACTION } from "@/views/pipe-network/constants";
import { deletePolyline, queryPolylines } from "@/api/pipe";
import { getAssetsFile } from "@/utils/map";
import { useLocalStore } from "@/views/layer/gismap/store";

const { L }: any = window;
const props = defineProps({
  deviceCategoryList: Array<any>,
});

const dialogVisible = ref<boolean | number>(false);
const polylineListRef = ref([]);
const circleMarkerPositionRef = ref();
const activePolylineRef = ref();
const map = useMap();
const mapStore = useMapStore();
const { mapAction } = storeToRefs(mapStore);
const localStore = useLocalStore();
const { visibleLineClassIds } = storeToRefs(localStore);
let timer;
const onClick = (e) => {
  const isConnectionTwoPointsAction =
    mapAction.value === MAP_ACTION.ADD_POINT_ONLINE;
  const isPointDevideLineAction =
    mapAction.value === MAP_ACTION.DEVIDE_LINE_WITH_POINT;
  const isMoveAction = mapAction.value === MAP_ACTION.MOVE;
  const isModifyInfoAction = mapAction.value === MAP_ACTION.EDIT;
  if (isConnectionTwoPointsAction) {
    mapStore.setAddedPipePointOnLine(e.latlng);
  }
  if (isPointDevideLineAction) {
    const latlngs = e.target.getLatLngs();
    mapStore.setPointDevideLine({
      point: e.latlng,
      lines: [
        [latlngs[0], e.latlng],
        [e.latlng, latlngs[1]],
      ],
    });
  }
  if (isMoveAction) {
    map.on("movestart", onMoveStart).on("moveend", onMoveEnd);
  }
  if (isModifyInfoAction) {
    const { lineId } = e.target.options.attribution;
    const obj = polylineListRef.value.find(
      (item: any) => item.lineId === lineId
    );
    if (obj) {
      mapStore.setEditingPipeLine(obj);
    }
  }
};
const onHover = (e) => {
  const isConnectionTwoPointsAction =
    mapAction.value === MAP_ACTION.ADD_POINT_ONLINE;
  if (isConnectionTwoPointsAction) {
    circleMarkerPositionRef.value = e.latlng;
    activePolylineRef.value = e.target.getLatLngs();
    timer && clearTimeout(timer);
  }
};
const onUnHover = () => {
  const isConnectionTwoPointsAction =
    mapAction.value === MAP_ACTION.ADD_POINT_ONLINE;
  if (isConnectionTwoPointsAction) {
    timer = setTimeout(() => {
      activePolylineRef.value = null;
      circleMarkerPositionRef.value = null;
      timer = null;
    }, 2000);
  }
};
const isSameLatlng = (latlngA, latlngB) => {
  return latlngA.lat === latlngB.lat && latlngA.lng === latlngB.lng;
};
const getWeight = (lineId) => {
  if (!activePolylineRef.value) {
    return 4;
  } else {
    return 4;
  }
};
const onMoveStart = (e) => {};
const onMoveEnd = (e) => {};
const getColor = (classId: string) => {
  const lineCategoryList = props.deviceCategoryList?.line;
  if (lineCategoryList) {
    const obj = lineCategoryList.find((item: any) => item.classId === classId);
    if (obj) {
      const { image } = obj;
      return image;
    }
  }
};

const getAllLines = () =>
  queryPolylines({ pageSize: 100000, pageIndex: 1, isPublish: true }).then(
    ({ data, errors, succeeded }) => {
      if (succeeded && Array.isArray(data?.items)) {
        polylineListRef.value = data.items
          .filter((item: any) => item.jsonGeom)
          .map((item: any) => {
            const { coordinates } = JSON.parse(item.jsonGeom);
            const [lng, lat] = coordinates[0];
            return {
              ...item,
              coordinates: coordinates.map((item: any) => [item[1], item[0]]),
              startPoint: [lat, lng],
              color: getColor(item.classId),
            };
          });
      }
    }
  );
const _deleteLine = (lineId: number) => {
  deletePolyline(lineId).then((res) => {
    if (res.succeeded) {
      ElMessage("删除成功！");
      getAllLines();
    } else {
      ElMessage("删除失败！");
    }
  });
};
onMounted(() => getAllLines());
onUnmounted(() => {
  map && map.off("movestart", onMoveStart).off("moveend", onMoveEnd);
});
watchEffect(() => {
  if (Array.isArray(visibleLineClassIds.value)) {
    polylineListRef.value.forEach((item: any) => {
      item.visible = visibleLineClassIds.value.includes(item.classId);
    });
  } else {
    polylineListRef.value.forEach((item: any) => {
      item.visible = true;
    });
  }
});
</script>

<template v-if="positionRef">
  <LPolyline
    :key="lineId"
    v-for="{ coordinates, lineId, color } in polylineListRef.filter(
      (item: any) => item.visible !== false
    )"
    :lat-lngs="coordinates"
    :weight="getWeight(lineId)"
    :attribution="{ lineId }"
    :color="color"
    @click="onClick"
    @mouseover="onHover"
    @mouseout="onUnHover"
  />
  <LCircle
    v-if="circleMarkerPositionRef"
    :lat-lng="circleMarkerPositionRef"
    color="purple"
    :radius="30"
    weight="10"
    @click="onClick"
  />
  <template v-if="mapAction === MAP_ACTION.ADD_PIPELINE">
    <LCircle
      v-for="{ startPoint, lineId } in polylineListRef"
      :key="lineId"
      :lat-lng="startPoint"
      :radius="20"
      color="red"
      fill-color="white"
      :fillOpacity="0.3"
      :pacity="0.3"
      @click="
        (e: any) =>
          mapStore.setStartPointInfo({
            original: e.target.getLatLng(),
            latlng: e.latlng,
          })
      "
      @mouseover="
        (e: any) => {
          e.target.getElement().style.fillOpacity = 1;
          e.target.getElement().style.opacity = 1;
        }
      "
      @mouseout="
        (e: any) => {
          e.target.getElement().style.fillOpacity = 0.3;
          e.target.getElement().style.opacity = 0.3;
        }
      "
    />
  </template>
  <template v-if="mapAction === MAP_ACTION.DELETE">
    <LMarker
      v-for="{ startPoint, lineId } in polylineListRef"
      :lat-lng="startPoint"
      :key="lineId"
      :icon="
        L.divIcon({
          html: `<div style=&quot;width: 13px;height: 13px;cursor: pointer; position: relative; top: -7px; left: 17px; border: 1px solid;&quot;>
              <svg viewBox=&quot;0 0 40 40&quot; style=&quot;position: relative;left: 0px; top: -4px;&quot;>
                  <path stroke=&quot;#FF0000&quot; stroke-width=&quot;3&quot; d=&quot;M 10,10 L 30,30 M 30,10 L 10,30&quot; />
                  </svg>
              </div>`,
          className: 'abc',
        })
      "
      @click="dialogVisible = lineId"
    />
  </template>
  <el-dialog v-model="dialogVisible" title="提示" width="500">
    <span>确认删除吗？</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="
            _deleteLine(dialogVisible);
            dialogVisible = false;
          "
        >
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss"></style>
